<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">用户管理</h1>
          <p class="mt-1 text-sm text-gray-600">管理系统用户账号，包括管理员和学生账号</p>
        </div>
        <div class="flex items-center gap-3">
          <button
            @click="showAddModal = true"
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <PlusIcon class="w-4 h-4 mr-2" />
            添加用户
          </button>
          <button
            @click="refreshData"
            class="inline-flex items-center px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <ArrowPathIcon class="w-4 h-4 mr-2" />
            刷新
          </button>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 mb-6 p-6">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">搜索用户</label>
          <div class="relative">
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索用户名、姓名或邮箱..."
              class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            />
            <MagnifyingGlassIcon class="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
          </div>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">用户角色</label>
          <select
            v-model="filters.role"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部角色</option>
            <option value="admin">管理员</option>
            <option value="student">学生</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">账号状态</label>
          <select
            v-model="filters.status"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
          >
            <option value="">全部状态</option>
            <option value="active">正常</option>
            <option value="disabled">禁用</option>
            <option value="pending">待激活</option>
          </select>
        </div>
        <div class="flex items-end">
          <button
            @click="resetFilters"
            class="w-full px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
          >
            重置筛选
          </button>
        </div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h2 class="text-lg font-medium text-gray-900">用户列表</h2>
          <div class="flex items-center gap-3">
            <span class="text-sm text-gray-500">共 {{ filteredUsers.length }} 个用户</span>
            <button
              @click="exportUsers"
              class="text-sm text-blue-600 hover:text-blue-900 transition-colors"
            >
              导出数据
            </button>
          </div>
        </div>
      </div>
      
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <input
                  type="checkbox"
                  @change="toggleSelectAll"
                  :checked="selectedUsers.length === filteredUsers.length && filteredUsers.length > 0"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                用户信息
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                角色
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                状态
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                最后登录
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                创建时间
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="user in paginatedUsers" :key="user.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <input
                  type="checkbox"
                  :value="user.id"
                  v-model="selectedUsers"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center overflow-hidden">
                    <img v-if="user.avatar" :src="user.avatar" :alt="user.name" class="w-full h-full object-cover" />
                    <UserIcon v-else class="w-5 h-5 text-gray-400" />
                  </div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">{{ user.name }}</div>
                    <div class="text-sm text-gray-500">{{ user.username }}</div>
                    <div class="text-sm text-gray-500">{{ user.email }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="[
                  'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                  user.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'
                ]">
                  {{ getRoleText(user.role) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="[
                  'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                  user.status === 'active' ? 'bg-green-100 text-green-800' :
                  user.status === 'disabled' ? 'bg-red-100 text-red-800' :
                  'bg-yellow-100 text-yellow-800'
                ]">
                  {{ getStatusText(user.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ user.lastLogin ? formatDateTime(user.lastLogin) : '从未登录' }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ formatDateTime(user.createdAt) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex items-center gap-2">
                  <button
                    @click="editUser(user)"
                    class="text-blue-600 hover:text-blue-900 transition-colors"
                  >
                    编辑
                  </button>
                  <button
                    @click="toggleUserStatus(user)"
                    :class="[
                      'transition-colors',
                      user.status === 'active' ? 'text-red-600 hover:text-red-900' : 'text-green-600 hover:text-green-900'
                    ]"
                  >
                    {{ user.status === 'active' ? '禁用' : '启用' }}
                  </button>
                  <button
                    @click="resetPassword(user)"
                    class="text-orange-600 hover:text-orange-900 transition-colors"
                  >
                    重置密码
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, filteredUsers.length) }} 条，共 {{ filteredUsers.length }} 条
          </div>
          <div class="flex items-center gap-2">
            <button
              @click="currentPage--"
              :disabled="currentPage === 1"
              class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-sm">{{ currentPage }} / {{ totalPages }}</span>
            <button
              @click="currentPage++"
              :disabled="currentPage === totalPages"
              class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑用户弹窗 -->
    <div v-if="showAddModal || showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
        <div class="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 class="text-lg font-medium text-gray-900">
            {{ showAddModal ? '添加用户' : '编辑用户' }}
          </h2>
          <button
            @click="closeModal"
            class="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <XMarkIcon class="w-6 h-6" />
          </button>
        </div>
        <form @submit.prevent="saveUser" class="p-6">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
              <input
                v-model="userForm.username"
                type="text"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">姓名</label>
              <input
                v-model="userForm.name"
                type="text"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">邮箱</label>
              <input
                v-model="userForm.email"
                type="email"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">角色</label>
              <select
                v-model="userForm.role"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              >
                <option value="admin">管理员</option>
                <option value="student">学生</option>
              </select>
            </div>
            <div v-if="showAddModal">
              <label class="block text-sm font-medium text-gray-700 mb-2">初始密码</label>
              <input
                v-model="userForm.password"
                type="password"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
              <select
                v-model="userForm.status"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              >
                <option value="active">正常</option>
                <option value="disabled">禁用</option>
                <option value="pending">待激活</option>
              </select>
            </div>
          </div>
          <div class="flex justify-end gap-3 mt-6">
            <button
              type="button"
              @click="closeModal"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              取消
            </button>
            <button
              type="submit"
              class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
            >
              {{ showAddModal ? '添加' : '保存' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../../stores/app'
import {
  PlusIcon,
  ArrowPathIcon,
  MagnifyingGlassIcon,
  UserIcon,
  XMarkIcon
} from '@heroicons/vue/24/outline'

// 使用stores
const appStore = useAppStore()

// 响应式数据
const users = ref([])
const searchQuery = ref('')
const selectedUsers = ref([])
const showAddModal = ref(false)
const showEditModal = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

const filters = ref({
  role: '',
  status: ''
})

const userForm = ref({
  id: null,
  username: '',
  name: '',
  email: '',
  role: 'student',
  status: 'active',
  password: ''
})

// 计算属性
const filteredUsers = computed(() => {
  let filtered = users.value
  
  if (searchQuery.value) {
    const search = searchQuery.value.toLowerCase()
    filtered = filtered.filter(user => 
      user.username.toLowerCase().includes(search) ||
      user.name.toLowerCase().includes(search) ||
      user.email.toLowerCase().includes(search)
    )
  }
  
  if (filters.value.role) {
    filtered = filtered.filter(user => user.role === filters.value.role)
  }
  
  if (filters.value.status) {
    filtered = filtered.filter(user => user.status === filters.value.status)
  }
  
  return filtered
})

const totalPages = computed(() => {
  return Math.ceil(filteredUsers.value.length / pageSize.value)
})

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

// 方法
const refreshData = async () => {
  try {
    await loadUsers()
    appStore.showNotification('数据刷新成功', 'success')
  } catch (error) {
    appStore.showNotification('刷新失败，请重试', 'error')
  }
}

const loadUsers = async () => {
  // 模拟加载用户数据
  users.value = [
    {
      id: 1,
      username: 'admin',
      name: '系统管理员',
      email: 'admin@example.com',
      role: 'admin',
      status: 'active',
      lastLogin: '2024-01-15T10:30:00',
      createdAt: '2024-01-01T00:00:00',
      avatar: null
    },
    {
      id: 2,
      username: '2024001',
      name: '张三',
      email: 'zhangsan@student.edu.cn',
      role: 'student',
      status: 'active',
      lastLogin: '2024-01-14T15:20:00',
      createdAt: '2024-01-10T00:00:00',
      avatar: null
    },
    {
      id: 3,
      username: '2024002',
      name: '李四',
      email: 'lisi@student.edu.cn',
      role: 'student',
      status: 'pending',
      lastLogin: null,
      createdAt: '2024-01-12T00:00:00',
      avatar: null
    },
    {
      id: 4,
      username: 'teacher01',
      name: '王老师',
      email: 'wangteacher@example.com',
      role: 'admin',
      status: 'active',
      lastLogin: '2024-01-13T09:00:00',
      createdAt: '2024-01-05T00:00:00',
      avatar: null
    }
  ]
}

const resetFilters = () => {
  filters.value = {
    role: '',
    status: ''
  }
  searchQuery.value = ''
  currentPage.value = 1
}

const toggleSelectAll = () => {
  if (selectedUsers.value.length === filteredUsers.value.length) {
    selectedUsers.value = []
  } else {
    selectedUsers.value = filteredUsers.value.map(user => user.id)
  }
}

const editUser = (user) => {
  userForm.value = {
    id: user.id,
    username: user.username,
    name: user.name,
    email: user.email,
    role: user.role,
    status: user.status,
    password: ''
  }
  showEditModal.value = true
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  userForm.value = {
    id: null,
    username: '',
    name: '',
    email: '',
    role: 'student',
    status: 'active',
    password: ''
  }
}

const saveUser = async () => {
  try {
    if (showAddModal.value) {
      // 添加用户
      const newUser = {
        id: Date.now(),
        ...userForm.value,
        lastLogin: null,
        createdAt: new Date().toISOString(),
        avatar: null
      }
      users.value.push(newUser)
      appStore.showNotification('用户添加成功', 'success')
    } else {
      // 编辑用户
      const index = users.value.findIndex(u => u.id === userForm.value.id)
      if (index !== -1) {
        users.value[index] = {
          ...users.value[index],
          ...userForm.value
        }
        appStore.showNotification('用户信息更新成功', 'success')
      }
    }
    closeModal()
  } catch (error) {
    appStore.showNotification('操作失败，请重试', 'error')
  }
}

const toggleUserStatus = async (user) => {
  try {
    const newStatus = user.status === 'active' ? 'disabled' : 'active'
    const index = users.value.findIndex(u => u.id === user.id)
    if (index !== -1) {
      users.value[index].status = newStatus
      appStore.showNotification(
        `用户已${newStatus === 'active' ? '启用' : '禁用'}`,
        'success'
      )
    }
  } catch (error) {
    appStore.showNotification('操作失败，请重试', 'error')
  }
}

const resetPassword = async (user) => {
  try {
    // 模拟重置密码
    appStore.showNotification(`已为用户 ${user.name} 重置密码`, 'success')
  } catch (error) {
    appStore.showNotification('重置密码失败，请重试', 'error')
  }
}

const exportUsers = () => {
  // 模拟导出功能
  appStore.showNotification('用户数据导出功能开发中', 'info')
}

const getRoleText = (role) => {
  const roleMap = {
    'admin': '管理员',
    'student': '学生'
  }
  return roleMap[role] || role
}

const getStatusText = (status) => {
  const statusMap = {
    'active': '正常',
    'disabled': '禁用',
    'pending': '待激活'
  }
  return statusMap[status] || status
}

const formatDateTime = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadUsers()
})
</script>